var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser'); //处理post请求数据

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var bokeRouter = require('./routes/boke'); //管理博客的路由

// var db=require('./servicebus/mongodbcurd')//引入db数据库操作
// console.log(db)
require('./servicebus/mongodb') //连接mongodb数据库

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public'))); //将public的文件夹托管出去 直接可以通过地址栏拿到里面的静态资源

// app.use('http://localhost:8081');
app.use(bodyParser.json()) //中间件支持json解析
app.use(bodyParser.urlencoded({ //post请求 通过中间件处理
  extended:true
}));

app.use('/', indexRouter); //根路径 /时 访问 indexRouter 路由
app.use('/users', usersRouter);
app.use('/boke', bokeRouter); //博客路由管理


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

app.listen(3000, () => console.log(`服务启动于http://127.0.0.1:3000`))

module.exports = app;
